package com.dmall.modules.admin.controller;

import com.dmall.common.utils.Result;
import com.dmall.common.utils.ShiroUtils;
import com.dmall.modules.admin.entity.AdminUser;
import com.dmall.modules.admin.service.AdminUserService;
import com.dmall.modules.admin.service.AdminUserTokenService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 后台登录相关
 * @author Chen 2017/12/7
 */
@RestController
public class AdminLoginController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private AdminUserTokenService adminUserTokenService;
    @Autowired
    private Producer producer;

    /**
     * 验证码，用户输错三次请求验证码
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws ServletException, IOException {
        //设置Cache 不存储不保存
        response.setHeader("Cache-Control", "no-store, no-cache");
        //返回值类型
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping(value = "/sys/login")
    public Result login(String username, String password, String captcha)throws IOException {
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equalsIgnoreCase(kaptcha)){
            return Result.error("验证码不正确");
        }
        //用户信息
        AdminUser user = adminUserService.queryByUserName(username);
        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            return Result.error("账号或密码不正确");
        }
        //账号锁定
        if(user.getStatus() == 0){
            return Result.error("账号已被锁定,请联系管理员");
        }
        //根据用户ID生成token，并保存到数据库
        Result r = adminUserTokenService.createToken(user.getId());
        return r;
    }


}
